package com.android.nearshop.app.activity.setting;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.common.TemplateActivity;
import com.android.nearshop.app.activity.main.MainIndexActivity;
import com.android.nearshop.app.activity.main.ShakeShopActivity;
import com.android.nearshop.app.widget.TitleBar;
import com.android.nearshop.app.widget.TitleBar.OnTitleClickListener;
import com.android.nearshop.business.cache.DataCacheManager;
import com.android.nearshop.io.protocol.in.BannerAction.ADV_TYPE;
import com.android.nearshop.util.NotifyListener;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-17
 * @see : 设置界面
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class SettingActivity extends TemplateActivity 
implements OnClickListener,OnCheckedChangeListener
{  
    private CheckBox setting_sound_switch;
    private CheckBox setting_adv_switch;
    private TextView setting_change_city;
    private PopupWindow selLocPopWin;
    private BroadcastReceiver mad = new BroadcastReceiver() {
		public void onReceive(Context arg0, Intent arg1) {
			updateViews();
		}
	};
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_setting);
        
        initViews();
        //add by huangyue 监听关闭广告
        try {
        	registerReceiver(mad,  new IntentFilter("ad.close"));
		} catch (Exception e) {
		}
        //end
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        updateViews();
    }
    
    private void dissPop()
    {
        if(selLocPopWin != null && selLocPopWin.isShowing())
        {
            selLocPopWin.dismiss();
        }
    }
    
    @Override
    public void onBackPressed() 
    {
    	if(selLocPopWin != null && selLocPopWin.isShowing())
    	{
    		dissPop();
    		return;
    	}
    	
    	if( getParent() instanceof MainIndexActivity)
        {
            ((MainIndexActivity)getParent()).onBackPressed();
        }
    }
    
    private void showSelLocPopWin()
    {
        if(selLocPopWin == null)
        {
            View contentView = LayoutInflater.from(this).inflate(R.layout.popview_clear_cache, null);
            selLocPopWin = new PopupWindow(contentView,ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT, true);
            selLocPopWin.setTouchable(true);
            selLocPopWin.setOutsideTouchable(true);
            
            contentView.findViewById(R.id.clear_cache_one).setOnClickListener(this);
            contentView.findViewById(R.id.clear_cache_five).setOnClickListener(this);
            contentView.findViewById(R.id.clear_cache_all).setOnClickListener(this);
            contentView.findViewById(R.id.pop_cancel).setOnClickListener(this);
            
            contentView.setOnKeyListener(new OnKeyListener()
            {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event)
                {
                    if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK)
                    {
                        dissPop();
                        ShakeShopActivity.isPopBack = true;
                    }
                    return false;
                }
            });
            
        }
        
        selLocPopWin.showAtLocation(getWindow().getDecorView(),Gravity.BOTTOM, 0, 0);
    }
    
    @Override
    protected void setupTitleBar(TitleBar titleBar)
    {
        titleBar.setTitle(R.string.tx_setting);
        titleBar.setRightVisible(false);
        titleBar.setLeftBg(R.drawable.red_button_bg);
        titleBar.setLeftImage(R.drawable.icon_shake_small_w);
        titleBar.setOnTitleClickListener(new OnTitleClickListener()
        {          
            @Override
            public void onLeftClick()
            {
                MainIndexActivity.gotoShake(SettingActivity.this,mTitleBar.getLeftImgView());
            }
            @Override
            public void onRightClick()
            {
                
            }
        },  true, false);
    }
    
    @Override
    protected ADV_TYPE getAdvType()
    {
        // 显示广告，如果打开且这页需要显示的话
        return ADV_TYPE.SUB;
    }
    
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	try{
    		unregisterReceiver(mad);
    	}catch (Exception e) {
		}
    }

    @Override
    public void onClick(View v)
    {
    	
        switch(v.getId())
        {
            case R.id.setting_change_city:
            {
                ChangeCityActivity.startActivity(this);
                break;
            }
            case R.id.setting_about:
            {
            	SettingFunctionActivity.startActivity(this, SettingFunctionActivity.ABOUT_US);
                break;
            }
            case R.id.setting_clear_cache:
            {
            	showSelLocPopWin();
                break;
            }
            case R.id.setting_report:
            {
            	SettingFunctionActivity.startActivity(this, SettingFunctionActivity.REPORT);
                break;
            }
            case R.id.setting_lastsee:
            {
            	SettingFunctionActivity.startActivity(this, SettingFunctionActivity.LAST_SEE);
                break;
            }
            case R.id.setting_help:
            {
            	SettingFunctionActivity.startActivity(this, SettingFunctionActivity.HELP);
                break;
            }
            case R.id.setting_protocol:
            {
            	SettingFunctionActivity.startActivity(this, SettingFunctionActivity.SERVICE);
                break;
            }
            case R.id.pop_cancel:
            {
                dissPop();
                break;
            }
            case R.id.clear_cache_one:
            {
                dissPop();
                showLoding(null, "正在清理...");
                DataCacheManager.getInstance().clearCacheAsyn(1, mClearShopNotifyer);
                break;
            }
            case R.id.clear_cache_five:
            {
                dissPop();
                showLoding(null, "正在清理...");
                DataCacheManager.getInstance().clearCacheAsyn(5, mClearShopNotifyer);
                break;
            }
            case R.id.clear_cache_all:
            {
                dissPop();
                showLoding(null, "正在清理...");
                DataCacheManager.getInstance().clearCacheAsyn(-1, mClearShopNotifyer);
                break;
            }
            case R.id.setting_check_version:
            {
                if(!MyApplication.getContext().isNetWorkAvailable())
                {
                    showNoNetworkDialog();
                    return;
                }
                showLoding(null, "版本检测...");
                if( getParent() instanceof MainIndexActivity)
                {
                    ((MainIndexActivity)getParent()).checkUpdate(new NotifyListener<Boolean>()
                    {
                        @Override
                        public void onSucceed(Boolean result)
                        {
                            hideLoding();
                            if(result)
                            {
                                showToast("您的版本已经是最新版本");
                            }
                            updateVersion();
                        }
                        @Override
                        public void onError(int resultCode)
                        {
                            hideLoding();
                            showToast("检测失败！");
                        }
                    });
                }
                break;
            }
        }
        
    }
    
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        switch(buttonView.getId())
        {
            case R.id.setting_adv_switch:
            {
                MyApplication.getContext().setAdvOn(isChecked);
                break;
            }
            case R.id.setting_audio_switch:
            {
                MyApplication.getContext().setSoundOn(isChecked);
                break;
            }
        }
    }
    
    private void initViews()
    {
        setting_sound_switch = (CheckBox)findViewById(R.id.setting_audio_switch);
        setting_adv_switch = (CheckBox)findViewById(R.id.setting_adv_switch);
        setting_change_city = (TextView)findViewById(R.id.setting_change_city);              
		setting_adv_switch.setOnCheckedChangeListener(this);
		setting_sound_switch.setOnCheckedChangeListener(this);
        setting_change_city.setOnClickListener(this);
        findViewById(R.id.setting_about).setOnClickListener(this);
        findViewById(R.id.setting_clear_cache).setOnClickListener(this);
        findViewById(R.id.setting_report).setOnClickListener(this);
        findViewById(R.id.setting_lastsee).setOnClickListener(this);
        findViewById(R.id.setting_protocol).setOnClickListener(this);
        findViewById(R.id.setting_check_version).setOnClickListener(this);
        findViewById(R.id.setting_help).setOnClickListener(this);
        
        updateVersion();
    }
    
    private void updateVersion()
    {
        PackageManager pm = getPackageManager();       
        try {
            TextView version = (TextView)findViewById(R.id.version_code);
            if(!MyApplication.getContext().isLastVer)
            {
                PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);                
                version.setText(getString(R.string.setting_version_tip) + pi.versionName);
            }else
            {
                version.setText("您的版本已经是最新版本");
            }
        } catch (NameNotFoundException e) 
        {
            e.printStackTrace();
        }
    }
    
    private void updateViews()
    {
        setting_adv_switch.setChecked(MyApplication.getContext().isAdvOn());
        setting_sound_switch.setChecked(MyApplication.getContext().isSoundOn());
    }
  
    private NotifyListener<Boolean> mClearShopNotifyer = new NotifyListener<Boolean>()
    {
        @Override
        public void onSucceed(Boolean result)
        {
            hideLoding();
            if(result)
            {               
                showToast("清理完成！");
            }else
            {
                showToast("清理失败！");
            }
        }

        @Override
        public void onError(int resultCode)
        {   
            
        }
    };
    
    public static Intent getStartActivity(Activity context)
    {        
        Intent intent = new Intent(context, SettingActivity.class);
        return intent;
    }
}
